package com.monolithiot.cdn.management.common.util;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 2018/11/24 Create by 郭文梁
 * ZipUtil
 * Zip文件工具类
 *
 * @author 郭文梁
 * @date 2018/11/24
 */
public class ZipUtil {
    /**
     * Zip文件解压
     *
     * @param file zip文件
     * @param path 解压路径
     * @return 解压文件的个数
     * @throws IOException IO异常
     */
    public static int unzip(File file, String path) throws IOException {
        ZipFile zipFile = new ZipFile(file);

        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        int count = 0;

        while (entries.hasMoreElements()) {
            count++;
            ZipEntry zipEntry = entries.nextElement();

            File targetFile = new File(path, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                boolean success = targetFile.mkdirs();
                if (!success) {
                    throw new IOException("创建目录：[" + targetFile.getAbsolutePath() + "]失败");
                }
            } else {
                if (!targetFile.getParentFile().exists()) {
                    boolean success = targetFile.getParentFile().mkdirs();
                    if (!success) {
                        throw new IOException("创建目录：[" + targetFile.getParentFile().getAbsolutePath() + "]失败");
                    }
                }

                boolean success = targetFile.createNewFile();
                if (!success) {
                    throw new IOException("创建文件：[" + targetFile.getAbsolutePath() + "]失败");
                }

                InputStream inputStream = null;
                FileOutputStream outputStream = null;
                try {
                    inputStream = zipFile.getInputStream(zipEntry);
                    outputStream = new FileOutputStream(targetFile);
                    IOUtils.copy(inputStream, outputStream);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }
            }
        }
        return count;
    }
}
